package com.socket.learing.example;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
public class ServiceSocket {

    public static final ExecutorService EXECUTOR_SERVICE = new ThreadPoolExecutor(20, 100, 600, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1000));

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(2000);
        while (true) {
            Socket accept = serverSocket.accept();
            EXECUTOR_SERVICE.execute(new TaskRun(accept));
        }
    }

    public static class TaskRun implements Runnable {

        private Socket accept;

        public TaskRun(Socket accept) {
            this.accept = accept;
        }

        @Override
        public void run() {
            log.info("客户端接入，IP：{},端口：{}", accept.getInetAddress(), accept.getPort());
            try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(accept.getInputStream()));
                 PrintStream printStream = new PrintStream(accept.getOutputStream())
            ) {
                while (true) {
                    String recive = bufferedReader.readLine();
                    if (recive == null) {
                        log.info("客户端已退出");
                        break;
                    }
                    log.info("收到客户端{}:{}发来消息：{}",accept.getInetAddress(),accept.getPort(),recive);
                    printStream.println("接收到数据长度：" + recive.length());
                }
            } catch (Exception e) {
                log.error("客户端异常退出：{}", e);
            } finally {
                try {
                    accept.close();
                } catch (IOException e) {
                    log.error("关闭流异常:{}", e);
                }
            }
        }
    }

}